package zfbpay

import (
	"fmt"

	"github.com/go-pay/gopay"
)

type (
	// Body is goPay.BodyMap
	Body struct {
		gopay.BodyMap
	}

	// BodyMapKV is key-value struct
	BodyMapKV struct {
		Key string
		Val any
	}
)

// NewBody return Body pointer
func NewBody() *Body {
	b := Body{
		BodyMap: make(gopay.BodyMap),
	}
	return &b
}

// BuildBodyMap return goPay.BodyMap
func (b *Body) BuildBodyMap(kvs ...BodyMapKV) gopay.BodyMap {
	bm := b.BodyMap
	if bm == nil {
		bm = make(gopay.BodyMap)
	}
	for _, kv := range kvs {
		bm.Set(kv.Key, kv.Val)
	}
	return bm
}

// SetSubject 设置商品标题/交易标题/订单标题/订单关键字等
func (b *Body) SetSubject(subject string) *Body {
	b.Set("subject", subject)
	return b
}

// SetOutTradeNo 设置商户网站唯一订单号
func (b *Body) SetOutTradeNo(outTradeNo string) *Body {
	b.Set("out_trade_no", outTradeNo)
	return b
}

// SetTotalAmount 设置订单总金额，单位为分, 100 = 1元
func (b *Body) SetTotalAmount(totalAmount int64) *Body {
	b.Set("total_amount", fmt.Sprintf("%.2f", float64(totalAmount)*0.01))
	return b
}

// SetProductCode 设置销售产品码，商家和支付宝签约的产品码
func (b *Body) SetProductCode(productCode ...string) *Body {
	code := "QUICK_MSECURITY_PAY"

	if len(productCode) > 0 && productCode[0] != "" {
		code = productCode[0]
	}
	b.Set("product_code", code)
	return b
}

// SetTimeoutExpress 设置该笔订单允许的最晚付款时间，逾期将关闭交易
func (b *Body) SetTimeoutExpress(timeoutExpress ...string) *Body {
	timeout := "5m"
	if len(timeoutExpress) > 0 && timeoutExpress[0] != "" {
		timeout = timeoutExpress[0]
	}
	b.Set("timeout_express", timeout)
	return b
}

// SetPassbackParams 设置公用回传参数，如果请求时传递了该参数，则返回给商户时会回传该参数
func (b *Body) SetPassbackParams(passbackParams string) *Body {
	b.Set("passback_params", passbackParams)
	return b
}

// SetNotifyURL 设置异步通知地址，支付宝服务器主动通知商户服务器里指定的页面http/https路径
func (b *Body) SetNotifyURL(notifyURL string) *Body {
	b.Set("notify_url", notifyURL)
	return b
}

// SetReturnURL 设置同步通知地址，支付宝服务器主动通知商户客户端里指定的页面http/https路径
func (b *Body) SetReturnURL(returnURL string) *Body {
	b.Set("return_url", returnURL)
	return b
}
